var modules = {};

function clearModuleForm() {
	$(".delModule").css("display", "none");
	$("#module-id").val("");
	$("#module-number").val("1");
	$("#fiber").dataTable().fnClearTable();
	$("#module-color ul").dropdown("value","0#ffffff");
}

function initiateTables() {
	$('#modules').dataTable({
		"bPaginate" : false,
		"bLengthChange" : false,
		"bFilter" : true,
		"bSort" : false,
		"bInfo" : false,
		"bAutoWidth" : false,
		"bFilter" : false,
		"bInfo" : false,
		"fnCreatedRow" : moduleRowBound,
		"oLanguage" : {
			"sEmptyTable" : "Нет ни одного модуля"
		},
		"aoColumns" : [{
			"sClass" : "ui-widget-content"
		}, {
			"sClass" : "ui-widget-content"
		}, {
			"sClass" : "ui-widget-content"
		}, {
			"sClass" : "ui-widget-content"
		}]
	});

	$("#params").dataTable({
		"bPaginate" : false,
		"bLengthChange" : false,
		
		"bSort" : false,
		"bInfo" : false,
		"bAutoWidth" : false,
		"bFilter" : false,
		"bInfo" : false,
		"fnCreatedRow" : paramRowBound,
		"oLanguage" : {
			"sEmptyTable" : "Параметры не заданы"
		},
		"aoColumns" : [{
			"sClass" : "ui-widget-content"
		}, {
			"sClass" : "ui-widget-content"
		}]
	});

	$('#fiber').dataTable({
		"bPaginate" : false,
		"bLengthChange" : false,
		"bFilter" : true,
		"bSort" : true,
		"bInfo" : false,
		"bAutoWidth" : false,
		"bFilter" : false,
		"bInfo" : false,
		"fnCreatedRow" : fiberRowBound,
		"oLanguage" : {
			"sEmptyTable" : "Нет ни одного волокна"
		},
		"aoColumns" : [{
			"sClass" : "ui-widget-content num-column"
		}, {
			"sClass" : "ui-widget-content"
		}, {
			"sClass" : "ui-widget-content"
		}],
		aoColumnDefs : [{
			bSortable : false,
			aTargets : [1, 2]
		}]
	});
}

function initiateModuleDialog() {
	$("#module-edit-form").dialog({
		autoOpen : false,
		height : 520,
		width : 700,
		title : "Информация о модуле",
		draggable : false,
		resizable : false,
		modal : true,
		dialogClass : "no-close",
		buttons : {
			DeleteModule : {
				class : "delModule",
				text : 'Удалить',
				click : function() {
					if (confirm("Вы уверены что хотите удалить модуль?")) {
						var id = $("#module-id").val();
						modules[id]['delete'] = true;
						bindModules();
						$(this).dialog("close");
					}
				}
			},
			"Сохранить" : saveModule,
			"Отмена" : function() {
				$(this).dialog("close");
			}
		},
	});
	var ul = CreateColorPicker();
    $("#module-color").html("").append(ul);
    ul.dropdown({ value: "0#ffffff", selector: "color", direction: "down"});
}

function fiberRowBound(nRow, aData, iDataIndex) {
    var ul = CreateColorPicker();
	$("td:eq(1)", nRow).html("").append(ul);
	ul.dropdown({ value: aData[1], selector: "color", direction: "up"});
	$("td:eq(2)", nRow).html("<a href='' class='fiber-delete-link'>Удалить</a>");
	$(nRow).attr("id", aData[2]);
	oTable = $("#fiber").dataTable();
	
	$("td.num-column", nRow).editable({
		"callback" : function(data) {
			if (!data.content) return;
			var aPos = oTable.fnGetPosition(data.$el.get(0));
			oTable.fnUpdate(data.content, aPos[0], aPos[1]);
		}
	});
}

function CreateColorPicker()
{
    var ul= $("<ul></ul>");
    for (var i =0;i < colors.length; i++)
    {
        var colParts = colors[i].split("#");
        var hasRing = colParts[0] == '1';
        var color = "#" + colParts[1];
        var li = $("<li data-color='" + colors[i] + "'></li>").append("<div class='colPick large' style='background-color:" + color+"'></div>")
            .append(hasRing ? "&nbsp;+кольцо" : "&nbsp;");
        ul.append(li);
    }

    return ul;
}

function moduleRowBound(nRow, aData, iDataIndex) {
    var colParts = aData[2].split("#");
    var hasRing = colParts[0] == '1';
    var color = "#" + colParts[1];
	$("td:eq(2)", nRow).html("<div class='colPick large' style='width: 60px; background-color:" + color + "'></div>" + (hasRing ? "&nbsp;+кольцо" : "&nbsp;"));
	
	$("td:eq(3)", nRow).html(
		"<a href='' class='module-edit-link' >Редактировать</a>&nbsp;&nbsp;"+
		"<a href='' class='module-copy-link' >Создать копию</a>");
	$(nRow).attr("id", aData[3]);
}

function bindModules() {
	$("#modules").dataTable().fnClearTable();
	$.each(modules, function(id, value) {
		if (value['delete'])
			return;
		var number = value['number'];
		var color = value['color'];
		var fiber = value['fiber'].length > 1 ? "Многоволоконный" : "Одноволоконный";
		$("#modules").dataTable().fnAddData([number, fiber, color, id]);
	});
}

function editModule(id) {
	var moduleInfo = null;
	$("#fiber").dataTable().fnClearTable();
	$(".delModule").css("display", "block");
	moduleInfo = modules[id];
	if (!moduleInfo)
		return false;
	$("#module-id").val(id);

    $("#module-color ul").dropdown("value", moduleInfo["color"]);

	$("#module-number").val(moduleInfo["number"]);
	for (var i = 0; i < moduleInfo["fiber"].length; i++)
		$("#fiber").dataTable().fnAddData(moduleInfo["fiber"][i]);
	$("#module-edit-form").dialog("open");
}

function saveModule() {
	var moduleId = $("#module-id").val();
	var moduleInfo = {};
	moduleInfo["number"] = $("#module-number").val();
	moduleInfo["color"] = $("#module-color ul").dropdown("value");
	moduleInfo["fiber"] = [];
	var tFiber = $("#fiber").dataTable();
	var fiberData = tFiber.fnGetData();
	if (fiberData.length == 0) {
		alert("Зачем вам кабель без волокна?");
		return;
	}
	fiberData.sort(function (a,b) { return a[0] - b[0]; });
	for (var i = 0; i < fiberData.length; i++) {
		var curFiber = fiberData[i];
		curFiber[1] = $("tbody tr:eq(" + i + ") td:eq(1) span.value", tFiber).data("color");
		moduleInfo["fiber"].push(fiberData[i]);
	}
	// Создание модуля
	if (moduleId == "")
		modules[guid()] = moduleInfo;

	// Редактирование модуля
	else
		modules[moduleId] = moduleInfo;

	bindModules();
	$("#module-edit-form").dialog("close");
}

function initiateCable($cable) {
	var params = {};
	if ($cable) {
		modules = $cable.modules;
		$.each($cable.params, function(id, value) {
			params[id] = value;
		});
		$("#cable-title").text($cable.title);
		$("#cable-desc").text($cable.description);
		$("#cable-attenuation").text($cable.attenuation == null ? "" : $cable.attenuation);
		bindModules();
	} else {
		modules = {};
		$("#delete-cable").css("display","none");

	}
	$.ajax({
		url : "include/cable_controller.php",
		method : "POST",
		data : {
			op : "params"
		}
	}).done(function(response) {
		var res = JSON.parse(response);
		var pTable = $("#params").dataTable();
		$.each(res, function(id, title) {
			var pVal = ( typeof (params[id]) == 'undefined') ? null : params[id];
			pTable.fnAddData([title, pVal, id]);});
	});

	$("#cable-title").editable();
	$("#cable-attenuation").editable();
	$("#cable-desc").editable();
}

function paramRowBound(nRow, aData, iDataIndex) {
	$(nRow).attr("id", aData[2]);
	$("td:eq(1)", nRow).editable({
		"callback" : function(data) {
			if (!data.content) return;
			var oTable = $("#params").dataTable();
			var aPos = oTable.fnGetPosition(data.$el.get(0));
			oTable.fnUpdate(data.content, aPos[0], aPos[1]);
		}
	});
}

function saveCable() {
	if (cableId == null) cableId = guid();
	var params = [];
	var pData = $("#params").dataTable().fnGetData();
	var title = $("#cable-title").html(), desc = $("#cable-desc").html(), att = $("#cable-attenuation").html().replace(',','.');
	for (var i = 0; i < pData.length; i++)
		params.push({
			id : pData[i][2],
			value : pData[i][1]
		});
	$.ajax({
		url : "include/cable_controller.php",
		method : "POST",
		data : {
			op : "set",
			id : cableId,
			"data" : JSON.stringify({
				title : (title == editPlaceholder? "" : title),
				description :(desc == editPlaceholder? "" : desc),
				attenuation: (att == editPlaceholder ? "null" : att),
				modules : modules,
				params : params
			})
		}
	}).done(function(response) {
		var result = JSON.parse(response);
		if (result.success)
			parent.$("body").trigger("cableSaved");
		else
			alert("Ошибка при сохранении: " + result.error);
	});
}

function deleteCable() {
	$.ajax({
		url : "include/cable_controller.php",
		method : "POST",
		data : {
			op : "del",
			id : cableId
		}
	}).done(function(response) {
		var result = JSON.parse(response);
		if (result.success)
			parent.$("body").trigger("cableDeleted");
		else
			alert("Ошибка при удалении: " + result.error);
	});
}

function cloneModule(id) {
	var module = $.extend(true, {}, modules[id]);
	module.number = getMaxIndex($("#modules"),0);
	for (var i = 0 ; i < module['fiber'].length; i++)
		module['fiber'][i][2] = guid();
	modules[guid()] = module;
	bindModules();
	
}

function getMaxIndex(table, cell) {
	var idx = 1;
	var cell = $("tbody tr:last td:eq("+cell+"):not(.dataTables_empty)", table);
	if (cell.length != 0) idx = parseInt(cell.html()) + 1; 
	return idx;
}